<template>
  <div class="job-listings-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">招聘信息</h1>
      <p class="page-subtitle">发现您的理想工作机会</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-filter-card" shadow="never">
      <!-- 搜索栏 -->
      <div class="search-section">
        <el-input v-model="searchQuery" placeholder="搜索职位、公司或关键词..." size="large" clearable @input="handleSearch">
          <template #append>
            <el-icon @click="handleSearch" style="cursor: pointer"><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-select v-model="filters.jobType" placeholder="职位类型" clearable @change="handleFilter">
              <el-option label="全部类型" value="" />
              <el-option label="服务员" value="服务员" />
              <el-option label="洗碗工" value="洗碗工" />
              <el-option label="洗车工" value="洗车工" />
              <el-option label="保姆" value="保姆" />
              <el-option label="保洁" value="保洁" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filters.salary" placeholder="薪资范围" clearable @change="handleFilter">
              <el-option label="全部薪资" value="" />
              <el-option label="面议" value="面议" />
              <el-option label="2K-3K" value="2K-3K" />
              <el-option label="3K-5K" value="3K-5K" />
              <el-option label="5K以上" value="5K以上" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filters.experience" placeholder="学历" clearable @change="handleFilter">
              <el-option label="不限" value="不限" />
              <el-option label="小学" value="小学" />
              <el-option label="初中" value="初中" />
              <el-option label="高中" value="高中" />
              <el-option label="专科" value="专科" />
              <el-option label="本科" value="本科" />
            </el-select>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- <CHANGE> 改为小卡片网格布局，一行显示多个卡片 -->
    <!-- 职位列表 -->
    <div class="jobs-grid" v-loading="loading">
      <el-empty v-if="list.length == 0" description="暂无招聘数据" />
      <el-row :gutter="16">
        <el-col :span="8" v-for="(item, index) in list" :key="index">
          <RouterLink :to="`/zhaopin/detail?id=${item.id}`" target="_blank" @click="item.clicked = true">
            <el-card class="job-card" shadow="hover">
              <div class="job-card-content" :class="[item.clicked ? 'viewed' : '']">
                <!-- 职位标题和薪资 -->
                <div class="job-header">
                  <h3 class="job-title">{{ item.title }}</h3>
                  <span class="job-salary">
                    <span v-if="item.minSalary > 0">{{ formatSalary(item.minSalary) }} - </span>
                    <span v-if="item.maxSalary > 0">{{ formatSalary(item.maxSalary) }}</span>
                    <div v-else>面议</div>
                  </span>
                </div>
                <!-- 公司信息 -->
                <div class="company-info" v-if="item.company">
                  <span class="company-name">{{ item.company }}</span>
                </div>
                <!-- 工作信息 -->
                <div class="job-info">
                  <div class="info-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ item.location }}</span>
                  </div>
                  <template v-for="itemPh in item.phoneNumbers">
                    <div class="info-item">
                      <div v-if="itemPh.name">
                        <el-icon><User /></el-icon>
                        <span>{{ itemPh.name }}</span>
                      </div>
                      <div v-if="itemPh.phone">
                        <el-icon :style="item.contactPerson ? 'margin-left: 10px' : 'margin-left: 0px'"><Phone /></el-icon>
                        <span> {{ itemPh.phone.substr(0x0, 0x03) }} ... </span>
                      </div>
                    </div>
                  </template>
                </div>
                <!-- 技能标签 -->
                <div class="skills-tags">
                  <el-tag v-for="skill in JSON.parse(item.tagsJson)" :key="skill" size="small" effect="plain">
                    {{ skill }}
                  </el-tag>
                </div>

                <!-- 发布时间 -->
                <div class="job-footer">
                  <span class="publish-time">{{ item.postedDate }}</span>
                  <div>{{ item.requirements }}</div>
                </div>
              </div>
            </el-card>
          </RouterLink>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="prev, pager, next" :page-size="10" :total="totalCount" @change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { Search, Location, User, Phone } from '@element-plus/icons-vue'
import { useHead } from '@vueuse/head'
import { fetchList, remove } from '@/apis/zhaopin'
import { useUserStore } from '@/stores/user'

import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const userStore = useUserStore()

const showAdminOpts = computed(() => {
  return userStore.showAdminOpts ?? false
})

// 设置页面标题和描述
useHead({
  title: '东川招聘信息 - 找工作',
  meta: [
    { name: 'description', content: '浏览最新的东川区招聘信息，找到适合您的工作机会。' },
    { name: 'keywords', content: '东川招聘, 工作, 职位, 求职' }
  ]
})
const totalCount = ref(0) // 假设总职位数为1000
const searchQuery = ref('') // 搜索关键词
const listQuery = {
  page: 1,
  pageSize: 12,
  keyword: ''
}
const list = ref<any>([])

const handleRemove = (obj: any) => {
  // 处理删除逻辑
  remove(obj.id)
    .then((response) => {
      let { code, message } = response.data
      if (code !== 200) {
        throw new Error(message || '删除失败')
      }
      // 删除成功后重新获取数据
      fetchData()
    })
    .catch((error) => {
      console.error('删除失败:', error)
    })
}

const fetchData = () => {
  // 模拟获取数据
  listQuery.keyword = searchQuery.value.trim()
  loading.value = true
  fetchList(listQuery)
    .then((response) => {
      let { code, result, message } = response.data
      if (code !== 200) {
        throw new Error(message || '获取职位数据失败')
      }
      if (result.page == 1) {
        list.value = [] // 清空列表
      }
      totalCount.value = result.total

      for (const item of result.items) {
        if (item.phoneNumbers) {
          item.phoneNumbers = JSON.parse(item.phoneNumbers)
        }
        list.value.push(item)
      }
    })
    .catch((error) => {
      console.error('获取职位数据失败:', error)
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  fetchData()
})

const filters = ref({
  jobType: '',
  salary: '',
  location: '',
  experience: ''
})

// 方法
const handleSearch = () => {
  fetchData()
}

const formatSalary = (num: number) => {
  // 处理数值为0的情况
  if (num === 0) return '0'

  // 大于等于1000时，转换为k单位
  if (num >= 1000) {
    // 除以1000，保留1位小数（如2500 → 2.5）
    const value = (num / 1000).toFixed(1)
    // 去除末尾的.0（如3000 → 3k 而非3.0k）
    return value.endsWith('.0') ? `${parseInt(value, 10)}k` : `${value}k`
  }
  // 小于1000时直接返回原数值
  return num.toString()
}

const handleFilter = () => {}

const handleCurrentChange = (currentPage: number, pageSize: number) => {
  listQuery.page = currentPage
  listQuery.pageSize = pageSize
  fetchData()
}
</script>

<style scoped>
.job-listings-container {
  max-width: var(--page-max-width);
  margin: 0 auto;
  padding: 24px;
  background-color: #f8fafc;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2563eb;
  margin-bottom: 8px;
  font-family: 'Space Grotesk', sans-serif;
}

.page-subtitle {
  font-size: 16px;
  color: #64748b;
  font-family: 'DM Sans', sans-serif;
}

.search-filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
}

.search-section {
  margin-bottom: 20px;
  width: 100%;
}

.filter-section .el-select {
  width: 100%;
}

/* <CHANGE> 新增小卡片网格样式 */
.jobs-grid {
  margin-bottom: 32px;
}

.job-card {
  margin-bottom: 16px;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 280px;
}

.job-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(37, 99, 235, 0.15);
  border-color: #2563eb;
}

.job-card-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.job-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
  flex: 1;
  margin-right: 8px;
  line-height: 1.4;
  font-family: 'Space Grotesk', sans-serif;
}

.job-salary {
  font-size: 14px;
  font-weight: 600;
  color: #0ea5e9;
  white-space: nowrap;
}

.company-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.company-name {
  font-size: 14px;
  color: #475569;
  font-weight: 500;
}

.job-info {
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
  font-size: 12px;
  color: #64748b;
}

.info-item .el-icon {
  font-size: 12px;
}

.skills-tags {
  margin-bottom: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
.viewed {
  color: #94a3b8;
  border: 1px solid #f1f5f9;
}
.skills-tags .el-tag {
  font-size: 11px;
  height: 20px;
  line-height: 18px;
}

.job-footer {
  margin-top: auto;
  padding-top: 8px;
  border-top: 1px solid #f1f5f9;
  display: -webkit-box;
  color: #555;
  -webkit-line-clamp: 4; /* 限制2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.publish-time {
  font-size: 11px;
  color: #94a3b8;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .jobs-grid .el-col {
    width: 50% !important;
    flex: 0 0 50% !important;
    max-width: 50% !important;
  }
}

@media (max-width: 768px) {
  .jobs-grid .el-col {
    width: 100% !important;
    flex: 0 0 100% !important;
    max-width: 100% !important;
  }

  .filter-section .el-col {
    width: 50% !important;
    flex: 0 0 50% !important;
    max-width: 50% !important;
    margin-bottom: 12px;
  }
}
</style>
